﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core.Utils;

namespace Cofe.Web.Feed
{
    public class FeedServiceBase<T> : IFeedService<T>
        where T : EventArgs
    {
        #region Constructor

        public FeedServiceBase()
        {
            Repository = new FeedRepository<T>(this);
            Links = new FeedLinkHelper<T>(this);
            Updater = new FeedUpdater<T>(this);
        }
        
        #endregion

        #region Methods

        public void NotifyRecentFeedChanged(object sender, FeedChangedEventArgs eventArgs)
        {
            RecentFeedId = eventArgs.NewFeedId;
            RecentFeedChanged(sender, eventArgs);            
            _knownFeedId.AddOrUpdate(eventArgs.NewFeedId.Id, eventArgs.NewFeedId);
            FileSystem.CleanUpCurrentFeedDirectory(eventArgs.NewFeedId);
        }

        private FeedId getRecentFeedId()
        {
            return Feed<T>.FromFileName(FeedDirectory.Current, FileSystem.GetLatestFeed(), this.Builder).FeedId;
        }

        #endregion

        #region Data

        private Dictionary<int, FeedId> _knownFeedId = new Dictionary<int, FeedId>();
        private FeedId _recentFeedId = null;

        #endregion

        #region Public Properties
        public FeedId RecentFeedId { get { return _recentFeedId ?? (_recentFeedId = getRecentFeedId()); } private set { _recentFeedId = value; } }
        public Dictionary<int, FeedId> KnownFeedId { get { return _knownFeedId; } }
        public IFeedFileSystemHelper FileSystem { get; set; }
        public IFeedLinkHelper<T> Links { get; set; }
        public IFeedBuilder<T> Builder { get; set; }
        public IFeedUpdater<T> Updater { get; set; }
        public IFeedRepository<T> Repository { get; set; }
        public event EventHandler<FeedChangedEventArgs> RecentFeedChanged = (o,s) => { };

        #endregion


    }
}
